package com.xuliucar.car.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.tqltech.tqlpencomm.Dot;
import com.tqltech.tqlpencomm.PenCommAgent;
import com.tqltech.tqlpencomm.listener.TQLPenSignal;
import com.xuliucar.car.app.App;
import com.xuliucar.car.ui.fragment.EditHandwriting;

import java.text.SimpleDateFormat;
import java.util.Date;


public class BluetoothLEService extends Service {
    private final static String TAG = "USB_HOST";


    private String mBluetoothDeviceAddress;
    private int mConnectionState = STATE_DISCONNECTED;
    int nInvalidPositionCount = 0;
    int nMaxInvalidPositionCount = 5;

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;

    public final static String ACTION_GATT_CONNECTED =
            "ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "ACTION_DATA_AVAILABLE";

    public final static String ACTION_PEN_STATUS_CHANGE =
            "ACTION_PEN_STATUS_CHANGE";

    public final static String RECEVICE_DOT = "RECEVICE_DOT";

    public final static String EXTRA_DATA =
            "COM.EXAMPLE.SONIXBLESAMPLE.EXTRA_DATA";

    public final static String DEVICE_DOES_NOT_SUPPORT_UART =
            "DEVICE_DOES_NOT_SUPPORT_UART";


    private PenCommAgent bleManager;


    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    public static int unsignedToBytes(byte a) {
        int b = ((a & 0xFF));
        return ((b));
    }

    public class LocalBinder extends Binder {
        public BluetoothLEService getService() {
            return BluetoothLEService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // After using a given device, you should make sure that BluetoothGatt.close() is called
        // such that resources are cleaned up properly.  In this particular example, close() is
        // invoked when the UI is disconnected from the Service.
        close();
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */
    public boolean initialize() {

        bleManager = PenCommAgent.GetInstance(getApplication());
        bleManager.setTQLPenSignalListener(mPenSignalCallback);

        if (!bleManager.isSupportBluetooth()) {
            Log.e(TAG, "Unable to Support Bluetooth");
            return false;
        }

        if (!bleManager.isSupportBLE()) {
            Log.e(TAG, "Unable to Support BLE.");
            return false;
        }
        return true;
    }

    public boolean connect(final String address) {
        if (address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && bleManager.isConnect(address)
            ///&& mBluetoothGatt != null
                ) {
            Log.d(TAG, "Trying to use an existing pen for connection.");

            return true;
        }

        Log.d(TAG, "Trying to create a new connection.");
        bleManager.connect(address);
        mBluetoothDeviceAddress = address;
        mConnectionState = STATE_CONNECTING;
//        EditHandwriting.Companion/= -1;
        EditHandwriting.Companion.setGCurPageID(-1);
//        int gCurPageID = EditHandwriting.gCurPageID;
//        gCurPageID = -1;
        return true;
    }

    public void disconnect() {
        bleManager.disconnect(mBluetoothDeviceAddress);
    }

    public void close() {
        if (bleManager == null) {
            return;
        }
        Log.w(TAG, "mBluetoothGatt closed");
        bleManager.disconnect(mBluetoothDeviceAddress);
        mBluetoothDeviceAddress = null;

        bleManager = null;
    }


    public void getPenStatus() {
        Log.d(TAG, "----------getPenStatus----------");
        bleManager.ReqPenStatus();
    }

    public static String timedate(Long time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        @SuppressWarnings("unused")
        //long lcc = Long.valueOf(time);
                int i = Integer.parseInt(String.valueOf(time));
        String times = sdr.format(new Date(i * 1000L));
        return times;
    }

    private void showMessage(String msg) {
        Log.e(TAG, msg);
    }

    /// ===========================================================
    private OnDataReceiveListener onDataReceiveListener = null;

    public interface OnDataReceiveListener {
        void onDataReceive(Dot dot);

        void onOfflineDataReceive(Dot dot);

        void onFinishedOfflineDown(boolean success);

        void onOfflineDataNum(int num);
    }

    public void setOnDataReceiveListener(OnDataReceiveListener dataReceiveListener) {
        onDataReceiveListener = dataReceiveListener;
    }

    private TQLPenSignal mPenSignalCallback = new TQLPenSignal() {

        @Override
        public void onConnected(int forceMax, String fwVersion) {
            Log.d(TAG, "TQLPenSignal had Connected");
            String intentAction;

            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;
            broadcastUpdate(intentAction);
            Log.i(TAG, "Connected to GATT server.");
            ////mBluetoothGatt.discoverServices());
        }

        @Override
        public void onDisconnected() {
            String intentAction;
            Log.d(TAG, "TQLPenSignal had onDisconnected");

            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            Log.i(TAG, "C.");
            broadcastUpdate(intentAction);

        }

        @Override
        public void onOfflineDataList(int offlineNotes) {
            if (onDataReceiveListener != null) {
                onDataReceiveListener.onOfflineDataNum(offlineNotes);
            }
        }

        @Override
        public void onStartOfflineDownload(boolean isSuccess) {
        }

        @Override
        public void onFinishedOfflineDownload(boolean isSuccess) {
            Log.d(TAG, "-------offline download success-------");
            if (onDataReceiveListener != null) {
                onDataReceiveListener.onFinishedOfflineDown(isSuccess);
            }
        }

        @Override
        public void onReceiveOfflineStrokes(Dot dot) {
            Log.d(TAG, dot.toString());
            if (onDataReceiveListener != null) {
                onDataReceiveListener.onOfflineDataReceive(dot);
            }
        }

        @Override
        public void onPenAuthenticated() {
        }

        @Override
        public void onPenAutoPowerOnSetUpResponse(boolean isSuccess) {
            if (isSuccess) {
                App.Companion.setMPowerOnMode(App.Companion.getTmp_mPowerOnMode());
//                App.mPowerOnMode = App.tmp_mPowerOnMode;
            }
            String intentAction = ACTION_PEN_STATUS_CHANGE;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }

        @Override
        public void onPenAutoShutdownSetUpResponse(boolean isSuccess) {
            if (isSuccess) {
                App.Companion.setMPowerOffTime(App.Companion.getTmp_mPowerOffTime());
//                App.mPowerOffTime = App.tmp_mPowerOffTime;
            }
            String intentAction = ACTION_PEN_STATUS_CHANGE;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }

        @Override
        public void onPenBeepSetUpResponse(boolean isSuccess) {
            if (isSuccess) {
                App.Companion.setMBeep(App.Companion.getTmp_mBeep());
//                App.mBeep = App.tmp_mBeep;
            }
            String intentAction = ACTION_PEN_STATUS_CHANGE;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }

        @Override
        public void onPenSensitivitySetUpResponse(boolean isSuccess) {
            if (isSuccess) {
                App.Companion.setMPenSens(App.Companion.getTmp_mPenSens());
//                App.mPenSens = App.tmp_mPenSens;
            }
            String intentAction = ACTION_PEN_STATUS_CHANGE;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }

        /// add
        @Override
        public void onPenNameSetupResponse(boolean isSuccess) {
            if (isSuccess) {
                App.Companion.setMPenName(App.Companion.getTmp_mPenName());
//                App.mPenName = App.tmp_mPenName;
            }
            String intentAction = ACTION_PEN_STATUS_CHANGE;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }

        @Override
        public void onPenTimetickSetupResponse(boolean isSuccess) {
            if (isSuccess) {
                App.Companion.setMTimer(App.Companion.getTmp_mTimer());
//                App.mTimer = App.tmp_mTimer;
            }
            String intentAction = ACTION_PEN_STATUS_CHANGE;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }

        @Override
        public void onReceiveDot(Dot dot) {
            Log.d(TAG, "bluetooth service recivice=====" + dot.toString());
            if (onDataReceiveListener != null) {
                onDataReceiveListener.onDataReceive(dot);
            }

//                String intentAction = RECEVICE_DOT;
//                Log.i(TAG, "Disconnected from GATT server.");
//                broadcastUpdate(intentAction);
        }

        @Override
        public void onReceivePenStatus(
                long timetick,
                int forcemax,
                int battery,
                int usedmem,
                boolean autopowerMode,
                boolean beep,
                short autoshutdownTime,
                short penSensitivity
        ) {
            Log.d(TAG, "PenStatus {timetick:" + timetick
                    + ", forcemax:" + forcemax
                    + ", battery:" + battery
                    + ", usedmem:" + usedmem
                    + ", autopowerMode:" + autopowerMode
                    + ", beep:" + beep
                    + ", autoshutdownTime:" + autoshutdownTime
                    + ", penSensitivity:" + penSensitivity
                    + "}");

            String time = "";
            long timeCurr = 0;
            if (timetick > 0) {
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //String str = format1.format(new java.util.Date());
                try {
                    Log.i(TAG, "sad222222");
                    //String str = "2010-01-02 00:00:00";
                    String str1 = "2010-01-01 00:00:00";
                    //Date d1 = format1.parse(str);
                    Date d2 = format1.parse(str1);

                    long timeOrig = d2.getTime();
                    timeCurr = (timeOrig + timetick) / 1000;

                } catch (Exception e) {
                }
            }
            App.Companion.setMBattery(battery);
//            App.mBattery = battery;
            App.Companion.setMUsedMem(usedmem);
//            App.mUsedMem = usedmem;
            App.Companion.setMTimer(timetick);
//            App.mTimer = timetick;
            App.Companion.setMPowerOnMode(autopowerMode);
//            App.mPowerOnMode = autopowerMode;
            App.Companion.setMPowerOffTime(autoshutdownTime);
//            App.mPowerOffTime = autoshutdownTime;
            App.Companion.setMBeep(beep);
//            App.mBeep = beep;
            App.Companion.setMPenSens(penSensitivity);
//            App.mPenSens = penSensitivity;
            App.Companion.setMPenName(bleManager.getPenName());
//            App.mPenName = bleManager.getPenName();

//            App.mBTMac = bleManager.getPenMAC();
            App.Companion.setMBTMac(bleManager.getPenMAC());

//            App.mFirmWare = bleManager.getPenFirmWare();
            App.Companion.setMFirmWare(bleManager.getPenFirmWare());
//            App.mMCUFirmWare = bleManager.getPenMCUFirmWare();
            App.Companion.setMMCUFirmWare(bleManager.getPenMCUFirmWare());
            String intentAction = ACTION_PEN_STATUS_CHANGE;
            Log.i(TAG, "Disconnected from GATT server." + timeCurr);
            broadcastUpdate(intentAction);
        }

        @Override
        public void onUpDown(boolean isUp) {

        }

        @Override
        public void onReceiveOIDFormat(int var1) {

        }
    };
}

